const initialState = {
  allList: [] as IChannel[],
  userList: [] as IChannel[],
  // 1. reducer函数中声明初始值, 保存选中的id
  currentId: 0,
};

export type ActionType =
  | { type: 'channel/saveList'; payload: IChannel[] }
  | { type: 'channel/saveUserList'; payload: IChannel[] }
  | { type: 'channel/delById'; payload: number }
  | { type: 'channel/addById'; payload: number }
  // 2. 扩展ActionType
  | { type: 'channel/setId'; payload: number };

function channelReducer(
  state = initialState,
  action: ActionType
): typeof initialState {
  switch (action.type) {
    case 'channel/saveList':
      return { ...state, allList: action.payload };
    case 'channel/saveUserList':
      return { ...state, userList: action.payload };

    case 'channel/delById':
      return {
        ...state,
        userList: state.userList.filter((item) => item.id !== action.payload),
      };
    case 'channel/addById':
      const newItem = state.allList.find((item) => item.id === action.payload);
      return {
        ...state,
        userList: [...state.userList, newItem as IChannel].sort(
          (a, b) => a.id - b.id
        ),
      };
    // 5. reducer函数完成更新的计算
    case 'channel/setId':
      return {
        ...state,
        currentId: action.payload,
      };
    default:
      return state;
  }
}

export default channelReducer;

export interface IChannel {
  id: number;
  name: string;
}
